package com.seres.util;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seres.constant.CommonKey;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Tan-Bowen
 * @version 1.0
 * @description TODO
 * @date 2021/7/27 14:53
 */
public class BaseController {

    /**
     * @param [request]
     * @return java.lang.String
     * @author Tan-Bowen
     * @description TODO 获取ip地址
     * @date 2021/7/27 14:54
     * @paramType [javax.servlet.http.HttpServletRequest]
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if (ip.contains(",")) {
                ip = ip.split(",")[0];
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public <T> Page<T> getPage(PageUtil.Pages param) {
        return new Page<T>().setCurrent(param.getCurrent()).setSize(param.getSize());
    }

    public Long getUser(HttpServletRequest request) {
        String userId = request.getHeader(CommonKey.USER_ID);
        ValidatorTools.commonThrow(StringUtils.isNotBlank(userId), "获取当前用户信息失败");
        return Long.valueOf(userId);
    }

}
